// 前端 roles 控制菜单权限 通过登录后的角色对菜单就行过滤处理
// 如果需要前端 roles 控制菜单权限 请使用此文件代码替换 permission.ts 的内容

import { cloneDeep } from 'es-toolkit'
import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'

import { UserRole } from '@/api/model/user'
import router, { allRoutes } from '@/router'
import { store } from '@/store'
import { PAGE_NOT_FOUND_ROUTE } from '@/utils/route/constant'

function filterPermissionsRouters(routes: Array<RouteRecordRaw>, roles: Array<string>) {
  const res: Array<RouteRecordRaw> = []
  const removeRoutes: Array<RouteRecordRaw> = []
  routes.forEach((route) => {
    const children: Array<RouteRecordRaw> = []
    route.children?.forEach((childRouter) => {
      // 宽松模式 无 roleCode 默认所有用户可访问
      const roleCode = childRouter.meta?.roleCode ?? '*'
      // 符合用户角色的路由 ‘*’ 表示所有用户都可访问
      if (roles.includes(roleCode) || roleCode === '*') {
        children.push(childRouter)
      }
      else {
        removeRoutes.push(childRouter)
      }
    })
    if (children.length > 0) {
      route.children = children
      res.push(route)
    }
  })
  res.push(PAGE_NOT_FOUND_ROUTE)
  return { accessedRouters: res, removeRoutes }
}

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    whiteListRouters: ['/login', '/temp'],
    routers: [] as Array<RouteRecordRaw>,
    removeRoutes: [] as Array<RouteRecordRaw>,
  }),
  actions: {
    async initRoutes(roles: Array<UserRole>) {
      const clonedAllRoutes = cloneDeep(allRoutes)
      let accessedRouters = []

      let removeRoutes: Array<RouteRecordRaw> = []
      // special token
      if (roles.includes(UserRole.ADMIN)) {
        accessedRouters = clonedAllRoutes
      }
      else {
        const res = filterPermissionsRouters(clonedAllRoutes, roles)
        accessedRouters = res.accessedRouters
        removeRoutes = res.removeRoutes
      }

      this.routers = accessedRouters
      this.removeRoutes = removeRoutes
      // console.log('accessedRouters', accessedRouters)
      console.log('removeRoutes', removeRoutes)
      removeRoutes.forEach((item: RouteRecordRaw) => {
        if (item.name && router.hasRoute(item.name)) {
          router.removeRoute(item.name)
        }
      })
    },
    async restore() {
      this.removeRoutes.forEach((item) => {
        if (item.name && !router.hasRoute(item.name)) {
          router.addRoute(item as RouteRecordRaw)
        }
      })
    },
  },
})

export function getPermissionStore() {
  return usePermissionStore(store)
}
